import requests
import validators

from flask import Blueprint, jsonify, request
from sqlalchemy.orm import sessionmaker

from model.base_model import engine, Testcase
from utils.log_utils import logger

testcase_bp = Blueprint('testcase', __name__, url_prefix='/api/testcase')


@testcase_bp.route('/add', methods=['POST'])
def add():
    try:
        # 解析请求数据
        req_data = request.json
        logger.info(f'请求数据===>{req_data}')
        if req_data.get('name').isspace():
            return jsonify(code=-1, msg='新增失败，请输入用例名称')
        elif set('[~!@#$%^&*()_+{}":;\']+$').intersection(req_data.get('name')):
            return jsonify(code=-1, msg='新增失败，用例名称请勿包含特殊字符')
        elif len(req_data.get('name')) > 30:
            return jsonify(code=-1, msg='新增失败，用例名称长度请勿超过30')
        elif not validators.url(req_data.get('url')):
            return jsonify(code=-1, msg='新增失败，请输入合法的url')
        elif req_data.get('method') == '':
            return jsonify(code=-1, msg='新增失败，请选择请求方式')
        new_case = Testcase(
            name=req_data.get('name'),
            url=req_data.get('url'),
            method=req_data.get('method'),
            params=req_data.get('params'),
            data=req_data.get('data')
        )

        # 会话
        Session = sessionmaker(bind=engine)
        db_session = Session()


        # 写入数据
        db_session.add(new_case)
        # 提交事务并关闭
        db_session.commit()
        db_session.close()
        return jsonify(code=0, msg='新增成功')
    except Exception as e:
        logger.warning(f'{e}')
        return jsonify(code=-1, msg=f'新增失败，原因：{e}')


@testcase_bp.route('/list', methods=['GET'])
def get():
    try:
        # 会话
        Session = sessionmaker(bind=engine)
        db_session = Session()
        # 查询表记录
        cases = db_session.query(Testcase).all()
        cases_list = [case.as_dict() for case in cases]
        # 提交事务并关闭
        db_session.commit()
        db_session.close()
        return jsonify(code=0, data=cases_list, msg='查询成功')
    except Exception as e:
        logger.warning(f'{e}')
        return jsonify(code=-1, msg=f'查询失败，原因：{e}')


@testcase_bp.route('/update', methods=['POST'])
def update():  # 错误不报错
    # 解析请求数据
    req_data = request.json
    print('-----')
    update_id = req_data.get('id')
    if req_data.get('name').isspace():
        return jsonify(code=-1, msg='修改失败，请输入用例名称')
    elif set('[~!@#$%^&*()_+{}":;\']+$').intersection(req_data.get('name')):
        return jsonify(code=-1, msg='修改失败，用例名称请勿包含特殊字符')
    elif len(req_data.get('name')) > 30:
        return jsonify(code=-1, msg='修改失败，用例名称长度请勿超过30')
    elif not validators.url(req_data.get('url')):
        return jsonify(code=-1, msg='修改失败，请输入合法的url')
    elif req_data.get('method') == '':
        return jsonify(code=-1, msg='修改失败，请选择请求方式')

    # 会话
    Session = sessionmaker(bind=engine)
    db_session = Session()
    try:  # 可以用装饰器写
        # 直接更新
        case = db_session.query(Testcase).filter_by(id=update_id)
        if not case.first():
            return jsonify(code=-1, msg=f'更新失败，不存在id为{update_id}的测试用例')

        case.update(req_data)
        # 提交事务并关闭
        db_session.commit()
        db_session.close()
        return jsonify(code=0, msg='更新成功')
    except Exception as e:
        logger.warning(f'{e}')
        return jsonify(code=-1, msg=f'更新失败，原因：{e}')


@testcase_bp.route('/delete', methods=['POST'])
def delete():
    # 解析请求参数
    del_id = request.args.get("id")
    # 会话
    Session = sessionmaker(bind=engine)
    db_session = Session()
    try:
        # 查询
        case = db_session.query(Testcase).filter_by(id=del_id).first()
        if not case:
            return jsonify(code=-1, msg=f'删除失败，不存在id为{del_id}的测试用例')
        # 删除
        db_session.delete(case)
        # 直接删除
        # case = db_session.query(Testcase).filter_by(id=3).delete()
        db_session.commit()
        db_session.close()
        return jsonify(code=0, msg='删除成功')
    except Exception as e:
        logger.warning(f'{e}')
        return jsonify(code=-1, msg=f'删除失败，原因：{e}')


@testcase_bp.route('/debug', methods=['POST'])
def debug():
    try:
        debug_id = request.args.get("id")
        # 会话
        Session = sessionmaker(bind=engine)
        db_session = Session()

        # 查询
        debug_case = db_session.query(Testcase).filter_by(id=debug_id).first()
        if not debug_case:
            return jsonify(code=-1, msg=f'调试失败，不存在id为{debug_id}的测试用例')

        # 发送请求
        res = requests.request(method=debug_case.method, url=debug_case.url,
                               params=debug_case.params, data=debug_case.data)
        if res.status_code == 200:
            return jsonify(code=0, msg='请求成功')
        else:
            return jsonify(code=-1, msg=f'调试失败，响应状态码为{res.status_code}')

    except Exception as e:
        logger.warning(f'{e}')
        return jsonify(code=-1, msg=f'调试失败，原因：{e}')
